package com.sprucetec.live.service.impl;

import com.sprucetec.live.enums.SerialNoPrefixEnum;
import com.sprucetec.live.service.DistributedLocker;
import com.sprucetec.live.service.GenerateUniqueIdService;
import com.sprucetec.live.utils.GenerateUniqueId;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * @auther: Wangshaobo
 * @date: 2018/11/23 14:18
 * @description:
 */
@Slf4j
@Service("generateUniqueIdService")
public class GenerateUniqueIdServiceImpl implements GenerateUniqueIdService {

    @Value("${unique.id.key}")
    private String uniqueIdKey;
    @Value("${unique.id.minLength}")
    private Integer uniqueIdMinLength;
    @Value("${LIVE_RESOURCE_LOCK}")
    private String LIVE_RESOURCE_LOCK;

    @Autowired
    private GenerateUniqueId generateUniqueId;

    @Autowired
    private DistributedLocker distributedLocker;


    @Override
    public String getUniqueId(SerialNoPrefixEnum prefixEnum) {
        log.info("getUniqueId method start with prefix::{}",prefixEnum);
        String uniqueId = "";
        try {
            //锁定资源
            RLock lock = distributedLocker.lock(LIVE_RESOURCE_LOCK, TimeUnit.SECONDS, 30);
            if (lock.isLocked()) {
                uniqueId = generateUniqueId.generateCode(uniqueIdKey, prefixEnum.getPrefix(), uniqueIdMinLength);
            }
        } catch (Throwable throwable) {
            log.error("getUniqueId method is error",throwable);
        } finally {
            //释放资源
            distributedLocker.unlock(LIVE_RESOURCE_LOCK);
        }

        return uniqueId;
    }
}
